<template>
  <!-- 聊天组件 -->
  <div class="chat">
    <Navbar :title="targetUserNickname || '聊天'" placeholder>
      <template #left>
        <div class="left" @click="handleClick">
          <Icon name="zuojiantou" size="18" color="#fff"></Icon>
        </div>
      </template>
    </Navbar>

    <!-- 聊天列表内容 -->
    <div class="chat_list" ref="chatListRef">
      <div v-for="msg in chatList" :key="msg._id || msg.createdAt" class="chat_item">
        <!-- 显示时间（仅当 showTime 为 true） -->
        <div v-if="msg.showTime" class="time">
          {{ msg.formattedTime }}
        </div>

        <!-- 左侧消息（对方发的） -->
        <div v-if="msg.fromId !== userId" class="item_left">
          <div class="avatar">
            <img :src="targetUserAvatar" loading="lazy" alt="对方头像" />
          </div>
          <div class="content">
            <div class="text">{{ msg.privateLetterContent || msg.content }}</div>
          </div>
        </div>

        <!-- 右侧消息（我发的） -->
        <div v-else class="item_right">
          <div class="content">
            <div class="text">{{ msg.privateLetterContent || msg.content }}</div>
          </div>
          <div class="avatar">
            <img :src="myAvatar" loading="lazy" alt="我的头像" />
          </div>
        </div>
      </div>
    </div>

    <!-- 输入栏 -->
    <div class="input_bar">
      <input type="text" ref="InputFocus" placeholder="发送消息..." v-model="inputContent" @keyup.enter="sendMessage" />
      <div class="input_bar_icon">
        <Icon name="aite" size="18" color="#fff" />
      </div>
      <div class="input_bar_icon" @click="sendMessage">
        <Icon name="dui" size="18" color="#fff" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, inject, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Navbar from '@/components/common/Navbar.vue'
import Icon from '@/components/common/Icon.vue'
import { formatTimeAgo } from '@/utils/time'
import { getChatListAPI, sendMessageAPI } from '@/api/message.js'
import { useUserStore } from '@/stores/userinfo'
import { useChatStore } from '@/stores/chatStore'

// 路由与用户信息
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const { userId, userAvatar: myAvatar } = userStore.userInfo

// 路由参数
const targetId = ref(route.query.targetId)
const targetUserNickname = ref(route.query.userNickname)
const targetUserAvatar = ref(route.query.userAvatar)


// DOM 引用
const chatListRef = ref(null)
const InputFocus = ref(null)
const inputContent = ref('')

// 聊天消息列表
const chatList = ref([])

// Socket
const socket = inject('socket')

// 格式化时间并添加 showTime 和 formattedTime
const processMessages = (messages) => {
  const sorted = [...messages].sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
  sorted.forEach((msg, index) => {
    // 格式化时间（如：2分钟前、昨天）
    msg.formattedTime = formatTimeAgo(msg.createdAt)

    // 是否显示时间分隔
    if (index === 0) {
      msg.showTime = true
    } else {
      const prev = sorted[index - 1]
      msg.showTime = !isSameDayAndHour(prev.createdAt, msg.createdAt)
    }
  })
  return sorted
}

// 判断是否同一天同一小时
const isSameDayAndHour = (time1, time2) => {
  const d1 = new Date(time1)
  const d2 = new Date(time2)
  return (
    d1.getDate() === d2.getDate() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getFullYear() === d2.getFullYear() &&
    d1.getHours() === d2.getHours()
  )
}

// 获取历史消息
const getChatList = async () => {
  try {
    const res = await getChatListAPI(userId, targetId.value)
    if (res.code === 200) {
      chatList.value = processMessages(res.data)
      nextTick(scrollToBottom)
    }
  } catch (error) {
    console.error('获取聊天记录失败:', error)
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatListRef.value) {
    chatListRef.value.scrollTo({
      top: chatListRef.value.scrollHeight,
      behavior: 'smooth'
    })
  }
}

// 发送消息
const sendMessage = async () => {
  const content = inputContent.value.trim()
  if (!content) return

  try {
    const res = await sendMessageAPI(userId, targetId.value, {
      content,
      fromUserId: userId,
      toUserId: targetId.value,
    })
    if (res.code === 200) {
      const newMsg = res.data
      chatList.value = processMessages([...chatList.value, newMsg])
      inputContent.value = ''
      nextTick(scrollToBottom)
      // ✅ 保存会话信息到 chatStore
      const chatStore = useChatStore()
      chatStore.addOrUpdateSession({
        targetId: targetId.value,
        userNickname: targetUserNickname.value,
        userAvatar: targetUserAvatar.value,
        lastMessage: newMsg.content || newMsg.privateLetterContent,
        lastTime: newMsg.createdAt,
        unreadCount: 0
      })

      // 通过 socket 广播（可选，如果后端已广播可省略）
      socket.emit('sendPrivateLetter', {
        ...newMsg,
        content: newMsg.content || newMsg.privateLetterContent
      })
    }
  } catch (error) {
    console.error('发送失败:', error)
  }
}

// Socket 监听新消息
const handleNewMessage = (data) => {
  console.log('【收到 socket 消息】', data)
  console.log('当前 userId:', userId)
  console.log('当前 targetId:', targetId.value)
  console.log('消息 toId:', data.toId, '=== userId?', data.toId === userId)
  console.log('消息 fromId:', data.fromId, '=== targetId?', data.fromId === targetId.value)

  if (data.toId === userId && data.fromId === targetId.value) {
    chatList.value = processMessages([...chatList.value, data])
    nextTick(scrollToBottom)
    // ✅ 更新会话信息（来自对方）
    const chatStore = useChatStore()
    chatStore.addOrUpdateSession({
      targetId: targetId.value,
      userNickname: targetUserNickname.value,
      userAvatar: targetUserAvatar.value,
      lastMessage: data.content || data.privateLetterContent,
      lastTime: data.createdAt,
      unreadCount: 1 // 因为是别人发的，未读+1
    })
  } else {
    console.log('❌ 消息不属于当前会话，已忽略')
  }
}

// 返回上一页
const handleClick = () => router.back()

// 生命周期
onMounted(() => {
  // ✅ 关键：告诉后端当前用户上线，绑定 socketId
  socket.emit('login', userId)
  getChatList()
  socket.on('receivePrivateLetter', handleNewMessage)
})

onUnmounted(() => {
  // 移除监听，防止内存泄漏
  socket.off('receivePrivateLetter', handleNewMessage)
})
</script>

<style lang="scss" scoped>
.chat_list {
  width: 100%;
  height: calc(100vh - 90px);
  overflow: auto;
  padding: 10px 8px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  background-color: #161622;
  z-index: 2025;

  &::-webkit-scrollbar {
    width: 0;
    height: 0;
  }

  .chat_item {
    display: flex;
    flex-direction: column;
    gap: 5px;
    text-align: center;
    margin-bottom: 10px;

    .time {
      font-size: 12px;
      color: #fff;
      font-weight: bold;
    }

    .item_left,
    .item_right {
      position: relative;
      display: flex;
      align-items: center;
      gap: 15px;
      padding: 5px 10px;
      border-radius: 5px;
      flex: 1;
      /* 关键：撑满空间 */
      // max-width: calc(100% - 60px);
      /* 防止过长 */
      overflow: hidden;
      /* 防止内容溢出 */
    }

    .item_left .content::before {
      display: block;
      position: absolute;
      top: 20px;
      left: -18px;
      border: 8px solid transparent;
      border-right: 14px solid #fff;
      content: '';
      // 旋转
      transform: rotate(-20deg);
      z-index: 22;
    }

    .item_right .content::before {

      display: block;
      position: absolute;
      top: 20px;
      right: -18px;
      border: 8px solid transparent;
      border-left: 14px solid #fff;
      content: '';
      // 旋转
      transform: rotate(20deg);
      z-index: 22;
    }


    .item_left {
      margin-right: auto;
    }

    .item_right {
      margin-left: auto;


    }

    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
      flex-shrink: 0;

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: cover;
        /* 图片不拉伸变形 */
      }
    }

    .content {
      position: relative;
      display: flex;
      flex-direction: column;
      gap: 5px;
      padding: 10px;
      border-radius: 5px;
      background-color: #fff;
      font-size: 14px;
      font-weight: bold;
      color: #000;
      white-space: pre-wrap;
      min-width: 30px;
      word-break: break-all;
      text-align: left;
      // 最小高度
      min-height: 40px;
    }
  }
}

.input_bar {
  width: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  height: 44px;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 2025;
  background: #1a1b20;
  border-top: 1px solid #292825cc;

  input {
    background: #1a1b20;
    -webkit-box-flex: 1;
    -ms-flex: 1;
    flex: 1;
    font-size: 14px;
    color: #e8e8e9;
    padding-left: 10px;
    caret-color: #face15;
  }

  .input_bar_icon {
    width: 44px;
    height: 44px;
    display: flex;
    justify-content: center;
    align-items: center;

  }
}
</style>